from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from .models import User
from django import http
from django_redis import get_redis_connection
import re
import json
import logging
logger = logging.getLogger('django')
from django.contrib.auth import login,authenticate,logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.conf import settings
from .models import Address
from celery_tasks.email.tasks import send_verify_email
from goods.models import SKU
from carts.utils import merge_cart_cookie_to_redis
# Create your views here.


class UsernameCountView(View):
    def get(self,request,username):
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e :
            logger.error('数据库访问失败!')
            return JsonResponse({
                'code':400,
                'errmsg':'数据库访问错误'
            })
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'count': count
        })

class MobileCountView(View):
    def get(self,request,mobile):
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            return JsonResponse({
                'code':400,
                'errmsg':'查询数据库错误'
            })
        return JsonResponse({
            'code':0,
            'errmsg':'ok',
            'count': count
        })

class RegisterView(View):
    def post(self,request):
        dict = json.loads(request.body.decode())
        username = dict.get('username')
        password = dict.get('password')
        password2 = dict.get('password2')
        mobile = dict.get('mobile')
        allow = dict.get('allow')
        sms_code_client = dict.get('sms_code')

        if not all([username,password,password2,mobile,allow,sms_code_client]):
            return http.JsonResponse({
                'code':400,
                'errmsg':'缺少必传参数'
            })
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            return http.JsonResponse({
                'code':400,
                'errmsg':'username格式错误'
            })
        if not re.match(r'^[a-zA-Z0-9]{6,20}$',password):
            return http.JsonResponse({
                'code': 400,
                'errmsg': '缺少必传参数'
            })
        if password != password2:
            return http.JsonResponse({
                'code': 400,
                'errmsg': '两次输入不对'
            })
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return http.JsonResponse({
                'code': 400,
                'errmsg': 'mobile格式错误'
            })
        if allow != True:
            return http.JsonResponse({
                'code': 400,
                'errmsg': 'allow格式有误'
            })
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)

        if not sms_code_server:
            return http.JsonResponse({
                'code': 400,
                'errmsg': '短信验证码过期'
            })
        if sms_code_client != sms_code_server.decode():
            return http.JsonResponse({
                'code': 400,
                'errmsg': '验证码有误'
            })

        try:
            user = User.objects.create_user(
                username=username,
                password=password,
                mobile=mobile,

            )
        except Exception as e:
            return http.JsonResponse({
                'code':400,
                'errmsg':'保存到数据库错误'
            })
        login(request,user)

        response = JsonResponse({
            'code': 0,
            'errmsg': 'ok'
        })
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
        return response

class LoginView(View):
    def post(self,request):
        dict = json.loads(request.body.decode())
        username = dict.get('username')
        password = dict.get('password')
        remembered = dict.get('remembered')

        if not all([username,password]):
            return JsonResponse({
                'code':400,
                'errmsg':'缺少必传参数'
            })
        user = authenticate(username=username,password=password)
        if user is None:
            return JsonResponse({
                'code':400,
                'errmsg':'用户名或密码错误'
            })

        login(request,user)
        if remembered != True:
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(None)

        response = JsonResponse({
            'code': 0,
            'errmsg': 'ok'
        })
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
        return merge_cart_cookie_to_redis(request, user, response)


class LogoutView(View):
    def delete(self,request):
        logout(request)
        response = JsonResponse({
            'code':0,
            'errmsg':'ok'
        })
        response.delete_cookie('username')
        return response




class UserInfoView(LoginRequiredMixin,View):
    def get(self,request):
        info_data = {
            'username':request.user.username,
            'mobile':request.user.mobile,
            'email':request.user.email,
            'email_active':request.user.email_active,
        }
        return JsonResponse({
            'code':0,
            'errmsg':'ok',
            'info_data':info_data
        })


class EmailView(View):
    def put(self,request):
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')
        if not email:
            return JsonResponse({
                'code':400,
                'errmsg':'缺少email参数'
            })
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$',email):
            return JsonResponse({
                'code':400,
                'errmsg':"参数email有误"
            })
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({
                'code':400,
                'errmsg':'添加邮箱失败'
            })
        email ='<' + email + '>'
        # token = request.user.generate_token()
        # verify_url = settings.EMAIL_VERIFY_URL + token
        verify_url = request.user.generate_verify_email_url()
        # verify_url = '邮箱验证链接'

        send_verify_email.delay(email,verify_url)

        return JsonResponse({
            'code':0,
            'errmsg':'ok'
        })

class VerifyEmailView(View):

    def put(self, request):

        # 1、提取验证请求中的查询字符串参数token
        token = request.GET.get('token')
        if not token:
            return JsonResponse({'code': 400, 'errmsg': 'token缺失！'})

        # 2、校验token值，获取用户身份
        user = User.check_verify_email_token(token)
        if not user:
            return JsonResponse({
                'code':400,
                'errmsg':'无效的token'
            })
        try:
            # 2.1 验证成功，修改email_active参数为True
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({
                'code':400,
                'errmsg':'激活邮件失败'
            })

        return JsonResponse({'code': 0, 'errmsg': 'ok'})

class CreateAddressView(View):
    def post(self,request):
        try:
            count = Address.objects.filter(user=request.user,
                                           is_deleted=False).count()
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': '获取地址数据出错'})

        if count >= 20:
            return JsonResponse({'code': 400,
                                 'errmsg': '超过地址数量上限'})

        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数email有误'})

        try:
            address = Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400,
                                 'errmsg': '新增地址失败'})
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return JsonResponse({'code': 0,
                             'errmsg': '新增地址成功',
                             'address': address_dict})

class AddressView(View):
    """用户收货地址"""

    def get(self, request):
        """提供地址管理界面
        """
        # 获取所有的地址:
        addresses = Address.objects.filter(user=request.user,
                                           is_deleted=False)

        # 创建空的列表
        address_dict_list = []
        # 遍历
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }

            # 将默认地址移动到最前面
            default_address = request.user.default_address
            if default_address.id == address.id:
                # 查询集 addresses 没有 insert 方法
                address_dict_list.insert(0, address_dict)
            else:
                address_dict_list.append(address_dict)

        default_id = request.user.default_address_id

        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'addresses': address_dict_list,
                             'default_address_id': default_id})


class UpdateDestroyAddressView(View):
    """修改和删除地址"""

    def put(self, request, address_id):
        """修改地址"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400,
                                  'errmsg': '缺少必传参数'})


        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                     'errmsg': '参数email有误'})

        # 判断地址是否存在,并更新地址信息
        try:
            Address.objects.filter(id=address_id).update(
                user = request.user,
                title = receiver,
                receiver = receiver,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email
            )
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400,
                                 'errmsg': '更新地址失败'})

        # 构造响应数据
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应更新地址结果
        return JsonResponse({'code': 0,
                             'errmsg': '更新地址成功',
                             'address': address_dict})

    def delete(self, request, address_id):
        """删除地址"""
        try:
            # 查询要删除的地址
            address = Address.objects.get(id=address_id)

            # 将地址逻辑删除设置为True
            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400,
                                 'errmsg': '删除地址失败'})

        # 响应删除地址结果
        return JsonResponse({'code': 0,
                             'errmsg': '删除地址成功'})

class DefaultAddressView(View):
    def put(self,request,address_id):
        try:
            address = Address.objects.get(id=address_id)
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({
                'code':400,
                'errmsg':'设置默认地址失败'
            })
        return JsonResponse({
            'code':0,
            'errmsg':'设置默认地址成功'
        })

class UpdateTitleAddressView(View):
    def put(self,request,address_id):
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        if not title:
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数！'})

        if len(title) > 20:
            return JsonResponse({'code': 400, 'errmsg': '地址名称格式不符！'})
        try:
            address = Address.objects.get(id=address_id)
            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({
                'code':400,
                'errmsg':'设置地址标题失败'
            })
        return JsonResponse({
            'code':0,
            'errmsg':'设置地址标题成功'
        })

class ChangePasswordView(LoginRequiredMixin,View):
    def put(self,request):
        dict = json.loads(request.body.decode())
        old_password = dict.get('old_password')
        new_password = dict.get('new_password')
        new_password2 = dict.get('new_password2')

        if not all([old_password,new_password,new_password2]):
            return JsonResponse({
                'code':400,
                'errmsg':'缺少必传参数'
            })
        result = request.user.check_password(old_password)
        if not result:
            return JsonResponse({
                'code':400,
                'errmsg':'原始密码不正确'
            })
        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return JsonResponse({
                'code': 400,
                'errmsg': '密码最少8位,最长20位'
            })
        if new_password != new_password2:
            return JsonResponse({
                'code':400,
                'errmsg':'两次输入密码不一致'
            })
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({
                'code': 400,
                'errmsg': '修改密码失败'
            })
        logout(request)
        response = JsonResponse({
            'code':0,
            'errmsg':'ok'
        })
        response.delete_cookie('username')
        return response

class UserBrowseHistory(View,LoginRequiredMixin):
    def post(self,request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            return JsonResponse({
                'code':400,
                'errmsg':'sku不存在'
            })
        redis_conn = get_redis_connection('history')
        p1 = redis_conn.pipeline()
        user_id = request.user.id

        p1.lrem('history_%s' % user_id,0,sku_id)
        p1.lpush('history_%s' % user_id,sku_id)
        p1.ltrim('history_%s' % user_id,0,4)
        p1.execute()
        return JsonResponse({
            'code':0,
            'errmsg':'ok'
        })

    def get(self,request):
        redis_conn = get_redis_connection('history')
        sku_ids = redis_conn.lrange('history_%s' % request.user.id,0,-1)
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append({
                'id':sku.id,
                'name':sku.name,
                'default_image_url':sku.default_image_url,
                'price':sku.price
            })
        return JsonResponse({
            'code':0,
            'errmsg':'ok',
            'skus':skus
        })